#include "Common.h"
#include "Resource.h"
#include "ResourceManager.h"
#include "NGLog.h"
#include "ChannelManager.h"
#include "WSSocket.h"
#include "WSSocketManager.h"
#include "WorldPacket.h"
#include "String.h"
#include "StringConverter.h"
#include "Users.h"
#include "UserManager.h"
#include "Character.h"
#include "CharManager.h"
#include "Towns.h"
#include "TownManager.h"
#include "ItemModelManager.h"
#include "GameDefine.h"
#include LOG_MGR_PATH
#include LOGIC_MGR_PATH
#include XMLDATA_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include "Message.h"
#include "json/json.h"
#include <openssl/evp.h>
#include "NoticeManager.h"
#include "Database/DatabaseEnv.h"
#include "AIInterface.h"
#include "GameServerCommand.h"
#include "Tools.h"

int SERVER_DECL script_process_world_server_command_notice(void * info)
{

	Json::Value * root = (Json::Value *)info;
	if(root)
		return SCR_ERROR;
	
	Json::Value data = (*root)["data"];
	// uint16 server_cmd = (*root)["server_cmd"].asUInt();
	// uint32 server_src = (*root)["server_dest"].asUInt();
	// uint32 server_dest = (*root)["server_dest"].asUInt();
	// uint32 server_type = (*root)["server_type"].asUInt();
	// uint32 server_parent = (*root)["server_parent"].asUInt();
		
	// String name = (data)["NAME"].asString();
	String msg = (data)["MSG"].asString();
	uint32 type= (data)["TYPE"].asUInt();
	sGLMgr.SendNotice(msg, type);
	return SCR_FORWARD_SUCCEED;
}

int SERVER_DECL script_world_server_hook_slave_close(uint32 serverid)
{
	// uint16 type = serverid >> 16;
	// uint16 id = serverid & 0x0000FFFF;
	sGLMgr.m_isCloseServer.SetVal(true);
	
	GameServer gs;
	// sChannelMgr.getBestLoginServer(gs);
	std::list<GameServer> lstGameServer;
	sChannelMgr.getAllServers(&lstGameServer);
	std::list<GameServer>::iterator it_server, endit_server = lstGameServer.end();
	for (it_server = lstGameServer.begin(); it_server!=endit_server; ++it_server)
	{
		if ((*it_server).flag & GameServerFlagMaster)
		{
			gs = *it_server;
			break;
		}
	}
	
	std::list<ResourcePtr> sList;
	sWSSocketMgr.getSocketList(sList);
	std::list<ResourcePtr>::iterator iter,enditer = sList.end();
	for (iter=sList.begin(); iter!=enditer; ++iter)
	{
		WSSocketPtr pSocket = (WSSocketPtr)*iter;
		if (pSocket.isNull())
			continue;
		CharPtr pChr = pSocket->getCurrentCharacter();
		if (pChr.isNull())
			continue;
		// if (pChr->getStatus() == CharacterStatusFree)
		// {
			WorldPacket packet;
			if (sProtocolsMgr.CreateLoginServerPacket(&packet, gs))
				pSocket->SendPacket(&packet);
		// }
	}
	Log.Debug("11","script_world_server_hook_slave_close serverid[%u] gs[%u]", serverid, gs.server_id);
	return true;
}

